package cn.edu.njuit.server.ugcnote.ugcnoteserver.security;

import cn.edu.njuit.server.ugcnote.ugcnoteserver.entity.UserInfo;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.service.AccountService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserDetailsService implements UserDetailsService {
    private final AccountService accountService;

    public SysUserDetailsService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //使用登录名从数据库中获得用户数据对象UserAccount
        UserInfo userAccount = accountService.getUser(username);
        if(userAccount!=null){
            //将用户角色组装成Springsecurity所需的
            List<SimpleGrantedAuthority> authorities=new ArrayList<>();
            SimpleGrantedAuthority authority=new SimpleGrantedAuthority("role_user");
            authorities.add(authority);
            //将账户数据对象构造成SpringSecurity需要的User对象。
            //构造User对象3个要素：
            //1、登录名
            //2、已加密的密码
            //3、用户所有的角色
            User user=new User(userAccount.getUserName(),userAccount.getUserPassword(),authorities);
            return user;
        }
        return null;
    }
}
